using System;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    public class TabWalletCtrl : MonoBehaviour
    {
        private TabWallet TabWallet;

        void Awake()
        {
            TabWallet = new TabWallet();
            TabWallet.BindProperties(transform);
            
            TabWallet.Banner.SetPageClickEvent(0, () =>
            {
                PanelLeaseDevices.Open();
            });
            TabWallet.Banner.SetPageClickEvent(1, () =>
            {
                PanelLeaseDevices.Open();
            });
            
            TabWallet.BtnCopyID.SetClick(() =>
            {
                CopyAndPaste.Copy(UserInfo.UserId);
                Tip.Open(CommAssets.instance.I18N_copy_success);
            });

            TabWallet.BtnRecharge.SetClick(() =>
            {
                PanelRecharge.Open();
            });

            TabWallet.BtnDetail.SetClick(() =>
            {
                PanelWalletDetail.Open();
            });

            TabWallet.BtnWithdraw.SetClick(() =>
            {
                PanelWithdraw.Open();
            });

            TabWallet.BtnMoreDeviceIncome.SetClick(() =>
            {
                PanelDeviceIncome.Open();
            });

            TabWallet.BtnMoreSalesIncome.SetClick(() =>
            {
                PanelSalesIncome.Open();
            });

            EventManager.Add<Event_UserInfoUpdate>(OnUserInfoUpdate);
        }

        private void OnEnable()
        {
            TabWallet.Page0.sprite = TabWallet.Page0.gameObject.Get<Sprite>((int)I18N.CurrLanguage);
            TabWallet.Page1.sprite = TabWallet.Page1.gameObject.Get<Sprite>((int)I18N.CurrLanguage);
            
            if (TabWallet.ScrollView)
            {
                TabWallet.ScrollView.verticalNormalizedPosition = 1;
            }
            ReqData();
        }

        private void OnUserInfoUpdate(Event_UserInfoUpdate e)
        {
            int level = (int)UserInfo.Info["level"];
            TabWallet.VIPText.text = CommAssets.instance.vipNames[level];

            TabWallet.WalletBalance.text = $"<color={Config.NumColor}>{I18N.Currency} <b><size=60>{StringHelper.Format2Decimal(UserInfo.total * 0.01f)}</size></b></color>";
            TabWallet.WalletDetail.text = $"{TabWallet.I18N_can_use}: <color={Config.NumColor}>{I18N.Currency} <b>{StringHelper.Format2Decimal(UserInfo.balance * 0.01f)}</b></color>";
            TabWallet.WalletDetail.text += "   |   ";
            TabWallet.WalletDetail.text += $"{TabWallet.I18N_cannot_use}: <color={Config.NumColor}>{I18N.Currency} <b>{StringHelper.Format2Decimal(UserInfo.remain * 0.01f)}</b></color>";
        }

        public async void ReqData()
        {
            TabWallet.VIPIcon.SetClick(() =>
            {
                PanelVIPRule.Open();
            });
            int level = (int)UserInfo.Info["level"];
            TabWallet.VIPText.text = CommAssets.instance.vipNames[level];

            //钱包
            var res = await Network.Get("/v1/user/wallet");
            JsonData wallet = res.jsonData["data"]["wallet"];
            TabWallet.TextID.text = $"ID:{wallet["user_id"]}";
            UserInfo.total = (int)wallet["balance"] + (int)wallet["income"] + (int)wallet["rewards"];
            UserInfo.balance = (int)wallet["balance"];
            UserInfo.remain = UserInfo.total - UserInfo.balance;
            OnUserInfoUpdate(new Event_UserInfoUpdate());

            //设备收益
            res = await Network.Get($"/v1/earnings/dash");
            JsonData data = res.jsonData["data"];
            JsonData earnings = data["earnings"];
            string[] xNames = new string[7];
            float[] yValues = new float[7];
            for (int i = 0; i < xNames.Length; i++)
            {
                DateTime dateTime = DateTime.Now.AddDays(-xNames.Length + i);
                xNames[i] = dateTime.ToString(I18N.MonthDayFormat);
                yValues[i] = 0;
            }
            int dataIndex = earnings.Count - 1;
            for (int i = xNames.Length - earnings.Count; i < xNames.Length; i++)
            {
                JsonData earning = earnings[dataIndex];
                xNames[i] = TimeHelper.Parse2Date(earning["date"].ToString(), false);
                string value = StringHelper.Format2Decimal((int)earning["income"] * 0.01f);
                yValues[i] = float.Parse(value);
                dataIndex--;
            }
            TabWallet.DeviceIncomeCart.GetComponent<Cart>().SetData(xNames, 0, 0, yValues);
            int totalIncome = (int)wallet["total_income"];
            int deviceCount = (int)wallet["bot_num"];
            int todayIncome = (int)data["todayIncome"];
            TabWallet.DeviceIncomeTitle.text = $"{TabWallet.I18N_total_income}：<color={Config.NumColor}>{I18N.Currency}{StringHelper.Format2Decimal(totalIncome * 0.01f)}</color>";
            TabWallet.DeviceIncomeTitle.text += "     ";
            TabWallet.DeviceIncomeTitle.text += $"{TabWallet.I18N_devices_count}：<color={Config.NumColor}>{deviceCount}</color>";
            TabWallet.DeviceIncomeTitle.text += "     ";
            TabWallet.DeviceIncomeTitle.text += $"{TabWallet.I18N_today_income}：<color={Config.NumColor}>{I18N.Currency}{StringHelper.Format2Decimal(todayIncome * 0.01f)}</color>";

            //分销收益
            JsonData commissions = data["commission"];
            string[] xNames2 = new string[7];
            float[] yValues2 = new float[7];
            for (int i = 0; i < xNames2.Length; i++)
            {
                DateTime dateTime = DateTime.Now.AddDays(-xNames2.Length + i);
                xNames2[i] = dateTime.ToString(I18N.MonthDayFormat);
                yValues2[i] = 0;
            }
            dataIndex = commissions.Count - 1;
            for (int i = xNames2.Length - commissions.Count; i < xNames2.Length; i++)
            {
                JsonData commission = commissions[dataIndex];
                xNames2[i] = TimeHelper.Parse2Date(commission["date"].ToString(), false);
                string value = StringHelper.Format2Decimal((int)commission["income"] * 0.01f);
                yValues2[i] = float.Parse(value);
                dataIndex--;
            }
            TabWallet.SalesIncomeCart.GetComponent<Cart>().SetData(xNames2, 0, 0, yValues2);
            int totalCommi = (int)wallet["total_commission"];
            int todayCommi = (int)data["todayCommission"];
            TabWallet.SalesIncomeTitle.text = $"{TabWallet.I18N_total_income}：<color={Config.NumColor}>{I18N.Currency}{StringHelper.Format2Decimal(totalCommi * 0.01f)}</color>";
            TabWallet.SalesIncomeTitle.text += "     ";
            TabWallet.SalesIncomeTitle.text += $"{TabWallet.I18N_today_income}：<color={Config.NumColor}>{I18N.Currency}{StringHelper.Format2Decimal(todayCommi * 0.01f)}</color>";
        }

        private void OnDestroy()
        {
            EventManager.Remove<Event_UserInfoUpdate>(OnUserInfoUpdate);
        }
    }
}
